package com.usian.comment.service.impl;

import com.usian.comment.feign.ApArticleFeign;
import com.usian.comment.feign.ApUserFeign;
import com.usian.comment.service.ApCommentService;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.comment.dtos.ApCommentVo;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import io.lettuce.core.GeoArgs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    private ApUserFeign apUserFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApArticleFeign apArticleFeign;

    @Override/*保存 评论*/
    public ResponseResult saveComment(CommentSaveDto dto) {

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        /*根据文章id查询*/
        ApArticle article = apArticleFeign.findArticleById(dto.getArticleId());
        if (article==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }

        /*通过本地线程获取id*/
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关注人不存在");
        }

        /*根据id 查询apUser*/
        ApUser apUser = apUserFeign.findUserById(user.getId());
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关注人不存在");
        }

        /*保存评论*/
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());  /*entryId 是文章的id*/
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override/* 保存 点赞某一个评论*/
    public ResponseResult like(CommentLikeDto dto) {

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        /*通过本地线程获取id*/
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"关注人不存在");
        }

        /*根据评论id查询 看看评论在不在*/
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论不存在");
        }

        /*判重 */
        List<ApCommentLike> apCommentLikeList = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId())), ApCommentLike.class);


        if (apCommentLikeList.size()==0) {
            if (dto.getOperation() == 0) {
                //更新评论的点赞数量
                apComment.setLikes(apComment.getLikes() + 1);
                mongoTemplate.save(apComment);

                //保存 APP评论信息点赞
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
            }
        }else if (apCommentLikeList.size()==1){
            ApCommentLike apCommentLike = apCommentLikeList.get(0);
            if (dto.getOperation()==1){
                //取消点赞
                //更新评论的点赞数量
                apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
                mongoTemplate.save(apComment);

                mongoTemplate.remove(apCommentLike);
            }
        }
        //5.返回点击的数量
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    @Override/*根据文章id查询评论列表 并看看用户点赞了哪个评论*/
    public ResponseResult findByArticleId(CommentDto dto) {

        if (dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }

        /*根据文章id查询*/
        ApArticle article = apArticleFeign.findArticleById(dto.getArticleId());
        if (article==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }

        /*根据文章id查询评论列表        根据文章id 和 评论创建时间小于  和 创建时间倒序  和分页  去查询 文章下的评论*/
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate())
        ).limit(10).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);

        /*判断用户登录了没有  没有登录直接返回评论信息*/
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.okResult(apCommentList);
        }

        /*获取评论的 所有id  去点赞表查*/
        List<String> commentIdList = apCommentList.stream().map(ApComment::getId).collect(Collectors.toList());

        /*查询点赞表   就是该用户点赞的所有评论*/
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("authorId").is(user.getId()).and("commentId").in(commentIdList));
        List<ApCommentLike> commentLikeList = mongoTemplate.find(query2, ApCommentLike.class);

        /*展示的集合*/
        List<ApCommentVo> result = new ArrayList<>();

        /*取评论表 和 点赞表 的交集  然后展示*/
       if (apCommentList.size()!=0 && commentLikeList.size()!=0){
           for (ApComment apComment : apCommentList) {
               /*封装*/
               ApCommentVo apCommentVo = new ApCommentVo();
               /*对象克隆*/
               BeanUtils.copyProperties(apComment,apCommentVo);
               for (ApCommentLike apCommentLike : commentLikeList) {
                   if (apComment.getId().equals(apCommentLike.getCommentId())){
                       apCommentVo.setOperation((short)0);  /*0点赞*/
                       break;
                   }else {
                       apCommentVo.setOperation((short)1);    /*1取消点赞*/
                       break;
                   }
               }
               result.add(apCommentVo);
           }
           return ResponseResult.okResult(result);
       }else {
           return ResponseResult.okResult(apCommentList);
       }
    }
}
